package org.start.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Server {

    public static ServerSocket start(int port) {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(60000);
            System.out.println("Server start at " + port);
            return serverSocket;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Server start failed");
            return null;
        }
    }

    public static String handleMsg(String msg) {
        if ("fqm".equals(msg)) {
            return "fqmyysjjd";
        } else if ("jj".equals(msg)) {
            return "fqmbjjzw";
        } else if ("dx".equals(msg)) {
            return "fqmyysjjddx";
        } else if ("exit".equals(msg)) {
            return "exit";
        } else {
            return "Server has received " + msg;
        }
    }

    public static void handleServer(Socket socket) throws IOException {
        while (true) {
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            String msg = dataInputStream.readUTF();
            System.out.println("收到来自" + socket.getInetAddress() + "的消息：" + msg);
            dataOutputStream.writeUTF(handleMsg(msg));
            if ("exit".equals(msg)) {
                System.out.println("Server exit");
                dataInputStream.close();
                dataOutputStream.close();
                socket.close();
                break;
            }
        }
    }

    public static void main(String[] args) {
        if (args.length == 0) {
            return;
        }

        try {
            final int port = Integer.parseInt(args[0]);
            ServerSocket serverSocket = start(port);
            if (serverSocket == null) {
                return;
            }
            Socket socket = serverSocket.accept();
            if (socket.isConnected()) {
                System.out.println("Server accept");
            } else {
                System.out.println("Server accept failed");
                return;
            }

            handleServer(socket);

            serverSocket.close();
        } catch (SocketException e) {
            System.out.println("Server start timeout");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
